package org.dant.ant.extension.tasks;

import java.io.*;
import java.util.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.tools.ant.Task;
import org.apache.tools.ant.TaskContainer;
import org.dant.ant.extension.tasks.commands.AntCommand;
import org.dant.ant.extension.tasks.internal.Endpoint;
import org.dant.ant.extension.tasks.internal.RemoteCommand;
import org.dant.ant.extension.utils.StringUtils;

public class RemoteAnt extends RemoteTask implements TaskContainer {

    protected File dir;
    protected String dirstring;

    private Vector nestedTasks = new Vector();
    private String buildContents;
    private ByteArrayOutputStream outstream = new ByteArrayOutputStream();

    public RemoteAnt() {
        rcmd = new AntCommand();
    }

    public void setDir(String d) {
        dirstring = d;
        this.dir = getProject().resolveFile(d, getProject().getBaseDir());
    }

    public File getDir() {
        return this.dir;
    }


    public String getBuildContents() {
        return buildContents;
    }

    private void parse() throws Exception {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        String defs = "/org/dant/ant/extension/tasks/xslt/spawn.xslt";
        Transformer transformer = tFactory.newTransformer(new StreamSource(this.getClass().getResourceAsStream(defs)));

        String targetName = getOwningTarget().getName();
        String taskName = getTaskName();

        transformer.setParameter("TARGET_ID", targetName);
        transformer.setParameter("TASK_ID", taskName);

        File source = StringUtils.parseFileName(getProject().getBaseDir(), getLocation().toString());

        transformer.transform(new StreamSource(source), new StreamResult(outstream));
        buildContents = outstream.toString();
        System.out.println(buildContents);
    }

    public void initialize() throws Exception {
        parse();
        super.initialize();
    }

    public void addTask(Task nestedTask) {
        nestedTasks.addElement(nestedTask);
    }

    public void resolveDir() throws IOException {
        for (Iterator iter = destHosts.keySet().iterator(); iter.hasNext();) {
            Endpoint ep = (Endpoint) iter.next();
            RemoteCommand request = (RemoteCommand)destHosts.get(ep);
            File basedir = ep.getBaseDir();
            File antdir = (dirstring == null) ? null : new File(dirstring);
            if (basedir == null || (antdir != null && antdir.isAbsolute())) {
                continue;
            }
            File absolutePath = fu.resolveFile(basedir, dirstring);
            request.appendParameters("dir", absolutePath);
        }
    }
}
